'use strict'

module.exports = app => {
  class TopicService extends app.Service {
    constructor(ctx) {
      super(ctx);
      this.root = 'https://cnodejs.org/api/v1';
    }
    async request(url, opts) {
      url = `${this.root}${url}`;
      opts = Object.assign({
        timeout: [ '30s', '30s' ],
        dataType: 'json',
      }, opts);
      return this.ctx.curl(url, opts);
    }

    async show(params) {
      const result = await this.app.mysql.get('article', {
        id: +params.id || 0,
      })
      return this.dealResult(result)
    }

    async list(params) {
      const { page, limit } = params
      const result = await this.app.mysql.select('article', {
        limit: +limit,
        offset: (page - 1) * limit,
      })
      return result;
    }

    async create(params) {
      const result = await this.app.mysql.insert('article', {
        title: params.title,
        content: params.content,
        images: JSON.stringify(params.images),
        type: params.type || 0,
        uid: params.uid,
        author: params.author || '',
      })
      return this.dealResult(result)
    }

    async update(params) {
      const result = await this.request('/topics/update', {
        method: 'post',
        data: params,
        contentType: 'json',
      });

      this.checkSuccess(result);
    }

    checkSuccess(result) {
      if (result.status !== 200) {
        const errorMsg = result.data && result.data.error_msg ? result.data.error_msg : 'unknown error';
        this.ctx.throw(result.status, errorMsg);
      }
      if (!result.data.success) {
        this.ctx.throw(500, 'remote response error', { data: result.data });
      }
    }

    dealResult(result) {
      if (!result) {
        this.ctx.throw(404, 'not exist id')
      } else if (result.affectedRows === 1) {
        result = result.insertId
      }


      return result
    }
  }

  return TopicService;
};
